﻿#Boa:Frame:FrameMain
#coding=utf-8

import wx
import wx.aui
import wx.lib.agw.flatnotebook as fnb

import FramePeer, DlgSystemConfig
#import FrameSO, FramePurOrder,FrameTableSO
#import DlgFinanceMain
import FramePurOrderShow
import FrameProduct
import DlgLogin

from config import *
from myLogger import *

import os, sys, datetime 
from dbmngr import *
from backup import *
from product import *

from permitManager import PermitManager
from constant import const

def create(parent):
    return FrameMain(parent)

[wxID_FRAMEMAIN, wxID_FRAMEMAINBTNEVENT, wxID_FRAMEMAINBTNLEND, 
 wxID_FRAMEMAINBTNNOTEBOOK, wxID_FRAMEMAINBTNPAYMENT, 
 wxID_FRAMEMAINBTNPURORDER, wxID_FRAMEMAINBTNPURQUERY, 
 wxID_FRAMEMAINBTNSALEORDER, wxID_FRAMEMAINBTNSALEQUERY, 
 wxID_FRAMEMAINBTNTEST, wxID_FRAMEMAINBTNVOUCHER, 
] = [wx.NewId() for _init_ctrls in range(11)]

[wxID_FRAMEMAINMENU2ITEMS0, wxID_FRAMEMAINMENU2ITEMS1, 
] = [wx.NewId() for _init_coll_menu2_Items in range(2)]

[wxID_FRAMEMAINMENU1ITEMS0, wxID_FRAMEMAINMENU1ITEMS1, 
] = [wx.NewId() for _init_coll_menu1_Items in range(2)]

class FrameMain(wx.Frame):
    def _init_ctrls(self, prnt):
        # generated method, don't edit
        wx.Frame.__init__(self, id=wxID_FRAMEMAIN, name=u'FrameMain',
              parent=prnt, pos=wx.Point(-8, -8), size=wx.Size(1288, 778),
              style=wx.DEFAULT_FRAME_STYLE,
              title=u'\u4e2a\u4f53\u6237\u6279\u53d1\u7ba1\u7406\u8f6f\u4ef6')
        self.SetClientSize(wx.Size(1280, 744))
        self.SetBackgroundStyle(wx.BG_STYLE_SYSTEM)
        self.Center(wx.HORIZONTAL)
        self.SetFont(wx.Font(12, wx.SWISS, wx.NORMAL, wx.BOLD, False,
              u'\u6977\u4f53_GB2312'))
        self.SetAutoLayout(False)
        self.SetBackgroundColour(wx.Colour(183, 209, 173))
        self.SetIcon(wx.Icon(u'./res/mfc.ico', wx.BITMAP_TYPE_ICO))
        self.Bind(wx.EVT_CLOSE, self.OnFrameMainClose)

        self.btnSaleOrder = wx.Button(id=wxID_FRAMEMAINBTNSALEORDER,
              label=u'\u9500\u552e\n\u8ba2\u5355', name=u'btnSaleOrder',
              parent=self, pos=wx.Point(2, 8), size=wx.Size(40, 40), style=0)
        self.btnSaleOrder.Enable(True)
        self.btnSaleOrder.Bind(wx.EVT_BUTTON, self.OnBtnSaleOrderButton,
              id=wxID_FRAMEMAINBTNSALEORDER)

        self.btnPurOrder = wx.Button(id=wxID_FRAMEMAINBTNPURORDER,
              label=u'\u91c7\u8d2d\n\u8ba2\u5355', name=u'btnPurOrder',
              parent=self, pos=wx.Point(2, 144), size=wx.Size(40, 40), style=0)
        self.btnPurOrder.Enable(True)
        self.btnPurOrder.Bind(wx.EVT_BUTTON, self.OnBtnPurOrderButton,
              id=wxID_FRAMEMAINBTNPURORDER)

        self.btnSaleQuery = wx.Button(id=wxID_FRAMEMAINBTNSALEQUERY,
              label=u'\u9500\u552e\n\u67e5\u8be2', name=u'btnSaleQuery',
              parent=self, pos=wx.Point(2, 48), size=wx.Size(40, 40), style=0)
        self.btnSaleQuery.Bind(wx.EVT_BUTTON, self.OnBtnSaleQueryButton,
              id=wxID_FRAMEMAINBTNSALEQUERY)

        self.btnEvent = wx.Button(id=wxID_FRAMEMAINBTNEVENT,
              label=u'\u4e8b\u4ef6\n\u63d0\u9192', name=u'btnEvent',
              parent=self, pos=wx.Point(2, 336), size=wx.Size(40, 40), style=0)
        self.btnEvent.Bind(wx.EVT_BUTTON, self.OnBtnEventButton,
              id=wxID_FRAMEMAINBTNEVENT)

        self.btnPurQuery = wx.Button(id=wxID_FRAMEMAINBTNPURQUERY,
              label=u'\u91c7\u8d2d\n\u67e5\u8be2', name=u'btnPurQuery',
              parent=self, pos=wx.Point(2, 184), size=wx.Size(40, 40), style=0)
        self.btnPurQuery.Bind(wx.EVT_BUTTON, self.OnBtnPurQueryButton,
              id=wxID_FRAMEMAINBTNPURQUERY)

        self.btnTest = wx.Button(id=wxID_FRAMEMAINBTNTEST, label=u'Test',
              name=u'btnTest', parent=self, pos=wx.Point(2, 528),
              size=wx.Size(40, 32), style=0)
        self.btnTest.Show(True)
        self.btnTest.Bind(wx.EVT_BUTTON, self.OnBtnTestButton,
              id=wxID_FRAMEMAINBTNTEST)

        self.btnVoucher = wx.Button(id=wxID_FRAMEMAINBTNVOUCHER,
              label=u'\u9500\u552e\n\u4ed8\u6b3e', name=u'btnVoucher',
              parent=self, pos=wx.Point(2, 88), size=wx.Size(40, 40), style=0)
        self.btnVoucher.Bind(wx.EVT_BUTTON, self.OnBtnVoucherButton,
              id=wxID_FRAMEMAINBTNVOUCHER)

        self.btnNotebook = wx.Button(id=wxID_FRAMEMAINBTNNOTEBOOK,
              label=u'\u5de5\u4f5c\n\u8bb0\u5f55', name=u'btnNotebook',
              parent=self, pos=wx.Point(2, 376), size=wx.Size(40, 40), style=0)
        self.btnNotebook.Bind(wx.EVT_BUTTON, self.OnBtnNotebookButton,
              id=wxID_FRAMEMAINBTNNOTEBOOK)

        self.btnLend = wx.Button(id=wxID_FRAMEMAINBTNLEND,
              label=u'\u540c\u884c\n\u62c6\u501f', name=u'btnLend', parent=self,
              pos=wx.Point(2, 280), size=wx.Size(40, 40), style=0)
        self.btnLend.Bind(wx.EVT_BUTTON, self.OnBtnLendButton,
              id=wxID_FRAMEMAINBTNLEND)

        self.btnPayment = wx.Button(id=wxID_FRAMEMAINBTNPAYMENT,
              label=u'\u91c7\u8d2d\n\u4ed8\u6b3e', name=u'btnPayment',
              parent=self, pos=wx.Point(2, 224), size=wx.Size(40, 40), style=0)
        self.btnPayment.Bind(wx.EVT_BUTTON, self.OnBtnPaymentButton,
              id=wxID_FRAMEMAINBTNPAYMENT)

    def __init__(self, parent):
        self._init_ctrls(parent)
        
        self.SetSize(Cfg.getFrameMainSize())
        self.Move(wx.Point(0, 0))
        
        self.nb = wx.aui.AuiNotebook(parent=self,pos=wx.Point(43, 10), 
                    size=wx.Size(1220, 675), 
                    style=wx.aui.AUI_NB_DEFAULT_STYLE|wx.aui.AUI_NB_WINDOWLIST_BUTTON|wx.aui.AUI_NB_CLOSE_BUTTON)
              
        #self.nb.SetBackgroundColour(wx.Colour(183, 209, 173))
        #self.SetFont(wx.Font(12, wx.SWISS, wx.NORMAL, wx.BOLD, False,
        #      u'\u6977\u4f53_GB2312'))
        self.nb.Bind(wx.aui.EVT_AUINOTEBOOK_PAGE_CLOSE, self.OnPageClosing)
        
        #self.initMenuBar()
        
        self.fPro = FrameProduct.create(self)        
        self.fPeer = FramePeer.create(self)   
        #self.fSO = FrameSO.create(self)
        self.fSaleOrderShow = None
        self.fPurList = None
        
        self.soList = []
        self.purList = []

##        self.nb = fnb.FlatNotebook(self, wx.ID_ANY, style=fnb.FNB_NODRAG)
##        self.nb.Move(wx.Point(8, 88))
##        self.nb.SetSize(wx.Size(1256, 624))
##        self.nb.SetFont(wx.Font(12, wx.SWISS, wx.NORMAL, wx.BOLD, False,
##              u'\u6977\u4f53_GB2312'))

        #p = wx.Panel(self.nb)
        #t = wx.StaticText(p, -1, u'Welcome to my shop!', (40,40))
        #self.homePage = u'首页'
        #self.nb.AddPage(p, self.homePage, True)
        
        self.CreateStatusBar()
        self.SetStatusText(u'状态显示栏')
        
        self.initMenuBar()
        
        self.loadHomePage()
        
        self.threadList = []
    
    def loadHomePage(self):
        import PanelHomePage
        self.homePage = u'导航主页面'
        self.nb.AddPage(PanelHomePage.PanelHomePage(self.nb), self.homePage, True)
        
    def OnPageClosing(self, event):
        if (self.nb.GetPageText(event.GetSelection()) == self.homePage):
            msg = u'不能关闭%s' %self.homePage
            dlg = wx.MessageDialog(self, msg,u'提示',wx.OK|wx.ICON_INFORMATION)
            dlg.ShowModal()
            event.Veto()
            return
            
##        dlg = wx.MessageDialog(self, u'即将关闭该标签页，请确认数据已经处理完毕?',u'提示',wx.YES_NO|wx.ICON_QUESTION)
##        if(dlg.ShowModal() == wx.ID_NO):
##            #donot shutup
##            event.Veto()
        if (not self.nb.GetPage(event.GetSelection()).doClose(False)):
            event.Veto()
            
    def initMenuBar(self):
        menuBar = wx.MenuBar()
        menuBar.SetFont(wx.Font(12, wx.SWISS, wx.NORMAL, wx.BOLD, False,
              u'\u6977\u4f53_GB2312'))
        menuBar.SetBackgroundColour(wx.Colour(183, 209, 173))
        
        menu1 = wx.Menu()
        item = menu1.Append(-1, u"销售订单")
        self.Bind(wx.EVT_MENU, self.OnBtnSaleOrderButton, item)  
        menu1.AppendSeparator()
        item = menu1.Append(-1, u"采购订单")
        self.Bind(wx.EVT_MENU, self.OnBtnPurOrderButton, item)
        menu1.AppendSeparator()
        item = menu1.Append(-1, u"同行拆借")
        self.Bind(wx.EVT_MENU, self.OnBtnLendButton, item)
        menuBar.Append(menu1, u"业务录入")
                
        menuFinance = wx.Menu()
        menu = menuFinance
        item = menu.Append(-1, u"资金账户")
        self.Bind(wx.EVT_MENU, self.OnBtnAccountButton, item)
        menu.AppendSeparator()
        item = menu.Append(-1, u"客户账务")
        self.Bind(wx.EVT_MENU, self.OnMenuFundCustomer, item)
        item = menu.Append(-1, u"供应商账务")
        self.Bind(wx.EVT_MENU, self.OnMenuFundSupplier, item)
        menuBar.Append(menuFinance, u"账务往来")
        
        menu = wx.Menu()
        item = menu.Append(-1, u"提醒事件")
        self.Bind(wx.EVT_MENU, self.OnBtnEventButton, item)
        menu.AppendSeparator()
        item = menu.Append(-1, u"工作记录")
        self.Bind(wx.EVT_MENU, self.OnBtnNotebookButton, item)
        menuBar.Append(menu, u"工作履历")
        
        menuBasic = wx.Menu()
        item = menuBasic.Append(-1, u"客户信息")
        self.Bind(wx.EVT_MENU, self.OnBtnParterButton, item)
        item = menuBasic.Append(-1, u"供应商信息")
        self.Bind(wx.EVT_MENU, self.OnBtnParterButton, item)
        item = menuBasic.Append(-1, u"同行信息")
        self.Bind(wx.EVT_MENU, self.OnBtnPeerButton, item)
        menuBasic.AppendSeparator()
        item = menuBasic.Append(-1, u"商品信息")
        self.Bind(wx.EVT_MENU, self.OnBtnProButton, item)
        menuBasic.AppendSeparator()
        item = menuBasic.Append(-1, u"公司信息")
        self.Bind(wx.EVT_MENU, self.OnMenuCompany, item)
        item = menuBasic.Append(-1, u"职员信息")
        self.Bind(wx.EVT_MENU, self.OnMenuStaff, item)
        menuBasic.AppendSeparator()
        item = menuBasic.Append(-1, u"权限管理")
        self.Bind(wx.EVT_MENU, self.OnMenuPrivileges, item)
        menuBar.Append(menuBasic, u"基本信息")
        
        menu2 = wx.Menu()
        item = menu2.Append(-1, u"资金账户")
        self.Bind(wx.EVT_MENU, self.OnMenuAccount, item)
        menu2.AppendSeparator()
        item = menu2.Append(-1, u"打印设置")
        self.Bind(wx.EVT_MENU, self.OnMenuPrint, item)
        menu2.AppendSeparator()
        item = menu2.Append(-1, u"备份与恢复")
        self.Bind(wx.EVT_MENU, self.OnMenuBackup, item)
        menuBar.Append(menu2, u"系统设置")
        
        menu = wx.Menu()
        item = menu.Append(-1, u"计算器")
        self.Bind(wx.EVT_MENU, self.OnMenuCalc, item)
        menu.AppendSeparator()
        item = menu.Append(-1, u"丝号对照表")
        self.Bind(wx.EVT_MENU, self.OnMenuWireTable, item)
        menuBar.Append(menu, u"工具")
        
        menuHelp = wx.Menu()
        item = menuHelp.Append(-1, u"系统日志")
        self.Bind(wx.EVT_MENU, self.OnBtnSyslogButton, item)
        menuHelp.AppendSeparator()
        item = menuHelp.Append(-1, u"每日警语")
        self.Bind(wx.EVT_MENU, self.OnMenuTip, item)
        menuHelp.AppendSeparator()
        item = menuHelp.Append(-1, u"关于软件")
        self.Bind(wx.EVT_MENU, self.OnMenuAbout, item)
        menuBar.Append(menuHelp, u"帮助")
        
        self.SetMenuBar(menuBar)
        self.menuBar = menuBar
    
    def setMenuAccess(self):
        if not PermitManager.accessTest(const.PERMIT_SYSMENU, refuseHit=False):
            #print ('disable menu bar')
            self.menuBar.Disable() #cannot work
                            
    def showWithChild(self):
        self.Maximize(False)
        if(self.fSaleOrderShow is not None):
            self.fSaleOrderShow.Maximize(False)
            
        if(self.fPurList is not None):
            self.fPurList.Maximize(False)
        
        for obj in self.soList:
            if(obj is not None):
                try:
                    obj.Maximize(False)
                except Exception,e:
                    print e
                    obj = None
        
        for obj in self.purList:
            if(obj is not None):
                try:
                    obj.Maximize(False)
                except Exception,e:
                    print e
                    obj = None
    
    def hideChild(self):
        
        if(self.fSaleOrderShow is not None):
            self.fSaleOrderShow.Iconize(True)
            
        if(self.fPurList is not None):
            self.fPurList.Iconize(True)
        
        for obj in self.soList:
            if(obj is not None):
                try:
                    obj.Iconize(True)
                except Exception,e:
                    print e
                    obj = None
        
        for obj in self.purList:
            if(obj is not None):
                try:
                    obj.Iconize(True)
                except Exception,e:
                    print e
                    obj = None
    
    def showProduct(self):
        self.fPro.Show()
        self.fPro.Raise()
                        
    def OnBtnProButton(self, event):
        #self.fPro.setShowState(self.fPro.STATE_CX)
        self.showProduct()

    def addPageSale(self, billId, draft=False):
        import PanelOrderSale
        
        p = PanelOrderSale.PanelOrderSale(self.nb)
        
        # 141016 设置客户会修改"当前页"标签标题，所以改为现加载页面，在加载订单
        #p.setEditBill(billId)
        #custName = p.m_peer.getValue(p.m_peer.COL_NAME)
        #title = u'销-%s' %custName
        
        self.nb.AddPage(p, '', True)
        p.setEditBill(billId, draft)
    
    def addPagePurchase(self, billId):
        import PanelOrderPurchase
        
        if not CDataPrivilege.requestAuth('create_pur'):
            return 
        
        p = PanelOrderPurchase.PanelOrderPurchase(self.nb)
        self.nb.AddPage(p, '', True)
        p.setEditBill(billId)
    
    def addPageVoucherEditor(self, voucherId):
        import PanelVoucher
        
        if not CDataPrivilege.requestAuth('edit_voucher'):
            return 
        
        p = PanelVoucher.PanelVoucher(self.nb, PanelVoucher.Type_Customer)
        self.nb.AddPage(p, u'收款单', True)
        p.setEditVoucher(voucherId)
        
        return p
    
    def addPageVoucher(self, billId='', peerObj=None):
        import PanelVoucher
        
        if not CDataPrivilege.requestAuth('create_voucher'):
            return 

        p = PanelVoucher.PanelVoucher(self.nb, PanelVoucher.Type_Customer)
        self.nb.AddPage(p, u'收款单',  True)
        #p.setSelectBill(billId)
        
        if (billId != ''):
            p.setSelectBill(billId)
        elif (peerObj is not None):
            p.setSelectPeer(peerObj)
            
        return p
    
    def addPagePaymentEditor(self, voucherId):
        import PanelVoucher
        
        if not CDataPrivilege.requestAuth('edit_voucher'):
            return 

        p = PanelVoucher.PanelVoucher(self.nb, PanelVoucher.Type_Supplier)
        self.nb.AddPage(p, u'付款单', True)
                        
        p.setEditVoucher(voucherId)
        return p
    
    def addPagePayment(self, billId='', peerObj=None):
        import PanelVoucher
        
        if not CDataPrivilege.requestAuth('create_voucher'):
            return 

        p = PanelVoucher.PanelVoucher(self.nb, PanelVoucher.Type_Supplier)
        self.nb.AddPage(p, u'付款单', True)
        #p.setSelectBill(billId)
        if (billId != ''):
            p.setSelectBill(billId)
        elif (peerObj is not None):
            p.setSelectPeer(peerObj)
            
        return p
    
    def newSaleOrder(self):
        import PanelOrderSale
        
        if not CDataPrivilege.requestAuth('create_sale'):
            return 
        
        p = PanelOrderSale.PanelOrderSale(self.nb)
        self.nb.AddPage(p, u'新销售单',True)
        return p
                                                    
    def OnBtnSaleOrderButton(self, event):
        '''允许多个订单页面同时打开，这意味着，self.fSO需要指向活动的页面，
            以便于与FramePro交互
            导致以上问题的原因是，framepro是唯一性的frame，而不是即时性的dialog
        '''
        #fSO = FrameSO.create(self.nb)
        #fSO.Show()
        #fSO.Raise()
        #self.soList.append(fSO)
        ##fSO.SetWindowStyle(wx.NO_BORDER)
        
        #super()产生一个super对象
        #fSO = super(FrameSO.FrameSO, fSO)
        #print type(fSO)
        
        #fSO.__class__ = wx.Panel
        #print type(fSO)
        
        # 141012 为了避免直接添加page造成的闪烁与位置变幻，先添加一个空白panel，
        #           再在panel上添加订单
        # 141012 根据首页位置设置page位置为(4,25)
        #
        #import PanelOrderSale
        #fSO = PanelOrderSale.PanelOrderSale(self.nb)
        #panel = wx.Panel(self.nb)
        #self.nb.AddPage(PanelOrderSale.PanelOrderSale(self.nb), u'新销售单',True)
        #PanelOrderSale.PanelOrderSale(self.nb)
        
        return self.newSaleOrder()
        
##        frame = FrameSO.create(self)
##        if (frame is None):
##            print 'None'
##            self.fSO.Raise()
##        else:
##            self.fSO = frame
##            self.fSO.Show()
        #self.fSO.Raise()

    def newPurOrder(self):
        import PanelOrderPurchase
        
        if not CDataPrivilege.requestAuth('create_pur'):
            return 
        
        self.nb.AddPage(PanelOrderPurchase.PanelOrderPurchase(self.nb), u'新采购单', True)
        
    def OnBtnPurOrderButton(self, event):
        '''采购订单'''
##        fPO = FramePurOrder.create(self)
##        fPO.Show()
##        fPO.Raise()
##        self.purList.append(fPO)
        #import PanelOrderPurchase
        #self.nb.AddPage(PanelOrderPurchase.PanelOrderPurchase(self.nb), u'新采购单', True)
        self.newPurOrder()
    
    def showCustomer(self):
        self.fPeer.Show()
        self.fPeer.Raise()
    
    def showSupplier(self):
        self.fPeer.Show()
        self.fPeer.Raise()
                
    def OnBtnParterButton(self, event):
        self.showCustomer()

    def showSaleHistory(self):
        import FrameSaleOrderShow       
                    
        if(self.fSaleOrderShow is None):
            self.fSaleOrderShow = FrameSaleOrderShow.create(self)
        if(self.fSaleOrderShow.IsIconized()):
            self.fSaleOrderShow.Maximize(False)
        self.fSaleOrderShow.Show()
        self.fSaleOrderShow.Raise()
        return self.fSaleOrderShow
    
    def showReport(self):
        import FrameReport
        
        if not CDataPrivilege.requestAuth('read_report'):
            return 
        
        if not self.__dict__.has_key('fReport'):
            self.fReport = FrameReport.create(self)
        frame = self.fReport
        if(frame.IsIconized()):
            frame.Maximize(False)
        frame.Show()
        frame.Raise()
        return frame  
    
    
    def showReportToday(self):
        import FrameReportToday
        
        if not CDataPrivilege.requestAuth('read_report'):
            return 
        
        frame = FrameReportToday.create(self)
        frame.Show()
        
    def showValidation(self):
        import FrameValidation
        
        if not self.__dict__.has_key('fValidation'):
            self.fValidation = FrameValidation.create(self)
        frame = self.fValidation
        if(frame.IsIconized()):
            frame.Maximize(False)
        frame.Show()
        frame.Raise()
        return frame  
    
        
    def showCustFund(self, peerObj):
        self.showSaleHistory()
        self.fSaleOrderShow.showCustFund(peerObj)
            
    def OnBtnSaleQueryButton(self, event):
        self.showSaleHistory()
            
    def OnBtnSystemConfigButton(self, event):
        dlg = DlgSystemConfig.create(self)
        dlg.Show()

    def OnBtnFinanceButton(self, event):
        dlg = DlgFinanceMain.create(self)
        dlg.Show()

    def OnFrameMainClose(self, event):
        if dbmngr.server_ip != '127.0.0.1':
            self.Destroy()
            return
        
        dlg = wx.MessageDialog(self, u'退出软件前请确保所有数据已经保存。是否退出软件?',u'提示',wx.YES_NO|wx.ICON_QUESTION)
        if(dlg.ShowModal() == wx.ID_NO):
            #donot shutup
            return
        else:
            #保存数据备份
            if (CDataBackup.isBackupQuit()):
                #dlg = wx.MessageDialog(self, u'正在保存备份，稍后将关闭软件',u'提示',wx.OK)
                #dlg.Show()
                #wx.Sleep(1)
                
                dlg = wx.MessageDialog(self, u'您设置了退出时自动备份，现在正在退出是否进行备份', u'提示', wx.YES_NO|wx.ICON_QUESTION)
                if(dlg.ShowModal() == wx.ID_YES):
                    retCode,msg,file = BackupManager.makeBackup()

                    #更新最近备份文件
                    if (file != ''):
                        CDataBackup.updateLastFile(file)
                    
                    if (retCode == BackupManager.SUCCEED):
                        style = wx.OK | wx.ICON_INFORMATION
                    else:
                        style = wx.OK | wx.ICON_ERROR
                                
                    dlg = wx.MessageDialog(self, msg, u'提示', style)
                    dlg.ShowModal()
                  
            self.Destroy()
            
            # 针对主窗口关闭后，控制台不关闭的情况，尝试关闭子线程
            for thread in self.threadList:
                print('try to stop', thread)
                thread.stop()

    def showEvent(self):
        import DlgEvent
        dlg = DlgEvent.create(self)
        dlg.ShowModal()
        
    def OnBtnEventButton(self, event):
        self.showEvent()

    def showPurHistory(self):
        if(self.fPurList is None):
            self.fPurList = FramePurOrderShow.create(self)
            
        if(self.fPurList.IsIconized()):
            self.fPurList.Maximize(False)
            
        self.fPurList.Show()
        self.fPurList.Raise()
        
    def OnBtnPurQueryButton(self, event):
        self.showPurHistory()

    def OnFrameMainIconize(self, event):
##        self.hideChild()
##        self.Iconize()
        event.Skip()

    def newCollect(self, collect=True):
        import PanelVoucher
        
        if not CDataPrivilege.requestAuth('create_voucher'):
            return 

        if collect:
            self.nb.AddPage(PanelVoucher.PanelVoucher(self.nb, PanelVoucher.Type_Customer), 
                        u'会款单', True)
        else:
            self.nb.AddPage(PanelVoucher.PanelVoucher(self.nb, PanelVoucher.Type_Supplier), 
                        u'付款单', True)

        
    def OnBtnVoucherButton(self, event):
        self.newCollect()

    def showAccountDetail(self):
        import PanelAccountDetail
        
        #if not PermitManager.accessTest(const.PERMIT_SETTING_ACCOUNTDETAIL):
        #    return
        
        if not CDataPrivilege.requestAuth('reconcliation'):
            return 
        
        title = u'资金账户'
        
        for i in range(self.nb.GetPageCount()):
            if (self.nb.GetPageText(i) == title):
                self.nb.SetSelection(i)
                return
        
        self.nb.AddPage(PanelAccountDetail.PanelAccountDetail(self.nb), 
                        title, True)
        
    def OnBtnAccountButton(self, event):
        self.showAccountDetail()

    def updateSO(self):
        # 重设sale order的paid
        for obj in CDataSaleOrder.m_dataList:
            total = obj.getValue(obj.COL_TOTAL)
            discount = obj.getValue(obj.COL_DISCOUNT)
            
            paid = CRelFundCustomer.getPaidAmount(obj.getValue(obj.COL_ID))
            unpaid = total - paid - discount
            
            #print 'id:%s (%g,%g)->(%g,%g)' %(obj.getValue(obj.COL_ID), obj.getValue(obj.COL_PAID),
            #            obj.getValue(obj.COL_UNPAID), paid, unpaid)
                        
            data = {obj.COL_PAID:paid,
                    obj.COL_UNPAID:unpaid}
            obj.setMulFieldVal(data)
            obj.update()
    
    def updateCustContact(self):
        '''把customer中的linkman lm_phone转移到customer_contact中'''
        for obj in CDataCustomer.m_dataList:
            lm = obj.getValue(obj.COL_LINKMAN)
            phone = obj.getValue(obj.COL_LMPHONE)
            peerId = obj.getValue(obj.COL_ID)
            
            if (lm == '' and phone == ''):
                continue
            
            cls = CDataCustomerContact
            data = {cls.iName:lm,
                cls.iPeerId:peerId,
                cls.iPhone:phone,
                cls.iMemo:''}

            obj = cls.factory()
            obj.setMulFieldVal(data)
            obj.insert()
    
    def updateCustLastOrder(self):
        '''更新customer中的lastOrder'''
        for obj in CDataCustomer.m_dataList:
            list = CDataSaleOrder.getBillAmount(obj.getValue(obj.COL_ID))
            if (not list or list[0][0] is None):
                continue
            
            billId = list[0][0]
            billObj = CDataSaleOrder.getFirstInstance({CDataSaleOrder.COL_ID:billId})
            obj.setValue(obj.COL_LASTORDER, billObj.getValue(billObj.COL_BILLDATE))
            obj.update()
                
    def OnBtnTestButton(self, event):
        import DlgTest
        dlg = DlgTest.create(self)
        dlg.ShowModal()
        
##        dlg = wx.MessageDialog(self, u'Begine Test?', u'提示', wx.YES_NO|wx.ICON_QUESTION)
##        if not(dlg.ShowModal() == wx.ID_YES):
##            return
##
##        #self.updateSO()
##        
##        self.updateCustContact()
##        self.updateCustLastOrder()
##        
##        dlg = wx.MessageDialog(self, u'Test Over!', u'提示')
##        dlg.ShowModal()

    def OnBtnToolButton(self, event):
        import DlgToolkitShaiWang
        
        DlgToolkitShaiWang.create(self).ShowModal()
        
    def setExpiredNum(self, num):
        label = u'事件\n(%d)' %num
        self.btnEvent.SetLabel(label)
        if (num > 0):
            self.btnEvent.SetForegroundColour(wx.RED)
        else:
            self.btnEvent.SetForegroundColour(wx.BLACK)

    def OnBtnPurFinanceButton(self, event):
        import DlgFundCustomer
        dlg = DlgFundCustomer.DlgFundCustomer(self.GetParent(), DlgFundCustomer.Type_Supplier)
        dlg.Show()

    def showRecord(self):
        import DlgRecord
        
        if not CDataPrivilege.requestAuth('read_report'):
            return 
        
        DlgRecord.create(self).ShowModal()
        
    def OnBtnNotebookButton(self, event):
        self.showRecord()

    def newLend(self):
        import PanelPeerLend        
        
        self.nb.AddPage(PanelPeerLend.PanelPeerLend(self.nb), u'同行拆借', True)
        
    def OnBtnLendButton(self, event):
        
        self.newLend()

    def OnBtnSyslogButton(self, event):
        import DlgLog
        DlgLog.create(self).ShowModal()

    def OnMenuPrint(self, event):
        import DlgTableSale
        
        if not PermitManager.accessTest(const.PERMIT_SETTING_PRINT):
            return
        
        DlgTableSale.create(self).ShowModal()
        
    def OnMenuBackup(self, event):
        import DlgBackupManager
        
        if not CDataPrivilege.requestAuth('edit_settings'):
            return 
        
        if not PermitManager.accessTest(const.PERMIT_SETTING_BACKUP):
            return
        
        DlgBackupManager.create(self).ShowModal()
        
    def OnMenuCompany(self, event):
        import FrameCompany
        
        if not PermitManager.accessTest(const.PERMIT_SETTING_COMPANY):
            return
        
        FrameCompany.create(self).Show()
        
    def OnMenuStaff(self, event):    
        import FrameStaff
        
        if not CDataPrivilege.requestAuth('edit_staff'):
            return 
        
        if not PermitManager.accessTest(const.PERMIT_SETTING_STAFF):
            return
        
        FrameStaff.create(self).Show()
    
    def OnMenuPrivileges(self, event):
        import DlgPrivileges
        
        if not CDataPrivilege.requestAuth('edit_privileges'):
            return 
        
        DlgPrivileges.create(self).ShowModal()
            
    def OnMenuAbout(self, event):
        import DlgAbout
        DlgAbout.create(self).ShowModal()
    
    def showAccount(self):
        import DlgAccount
        
        if not PermitManager.accessTest(const.PERMIT_SETTING_ACCOUNT):
            return
        
        DlgAccount.create(self).ShowModal()
            
    def OnMenuAccount(self, event):
        self.showAccount()

    def showPeer(self):
        import DlgPeer
        DlgPeer.create(self).ShowModal()
        
    def OnBtnPeerButton(self, event):
        self.showPeer()

    def showFundCustomer(self):
        #import DlgFundCustomer
        #DlgFundCustomer.create(self).ShowModal()
        
        import PanelFund
        
        dlg = wx.Dialog(self, -1, u'客户账务往来')
        panel = PanelFund.PanelFund(dlg, PanelFund.Type_Customer)
        #dlg.Fit() #适用于sizer
        dlg.SetClientSize(panel.GetSize())
        dlg.CenterOnScreen()
        dlg.ShowModal()
        dlg.Destroy()
        
    def OnMenuFundCustomer(self, event):
        self.showFundCustomer()
    
    def showFundSupplier(self):
        #import DlgFundCustomer
        #DlgFundCustomer.DlgFundCustomer(self, DlgFundCustomer.Type_Supplier).ShowModal()
        import PanelFund
        
        dlg = wx.Dialog(self, -1, u'供应商账务往来')
        panel = PanelFund.PanelFund(dlg, PanelFund.Type_Supplier)
        #dlg.Fit()
        dlg.SetClientSize(panel.GetSize())
        dlg.CenterOnScreen()
        dlg.ShowModal()
        dlg.Destroy()
        
    def OnMenuFundSupplier(self, event):
        self.showFundSupplier()
        
    def OnMenuTip(self, event):
        msg = u'请输入要建立的警句：'
        dlg = wx.TextEntryDialog(self, msg,caption=u'输入警句')

        if dlg.ShowModal() == wx.ID_OK:
            CDataTip.quickInsert({CDataTip.fi_tip:dlg.GetValue()})
            
    def OnMenuCalc(self, event):
        import os

        os.startfile('calc')
        
    def OnMenuWireTable(self, event):
        png = wx.Image(u'./res/丝号对照表.png', wx.BITMAP_TYPE_PNG).ConvertToBitmap()

        dlg = wx.Dialog(self, -1, u'丝号对照表')
        pngWireTable = wx.StaticBitmap(dlg, -1, png)
        dlg.SetClientSize(pngWireTable.GetBestSize())
        dlg.Centre()
        dlg.ShowModal()

    def OnBtnPaymentButton(self, event):
        
        if not CDataPrivilege.requestAuth('create_voucher'):
            return 
        
        self.newCollect(False)
        
    def appendThread(self, thread):
        self.threadList.append(thread)

    def newDeliveryPlan(self):
        import PanelDeliveryPlan
        
        if not CDataPrivilege.requestAuth('create_delievery'):
            return 

        self.nb.AddPage(PanelDeliveryPlan.PanelDeliveryPlan(self.nb), u'直送计划',True)
        
    def addPageDeliveryPlan(self, planId=-1):
        import PanelDeliveryPlan
        page = PanelDeliveryPlan.PanelDeliveryPlan(self.nb)
        if planId != -1:
            page.setEditData(planId)
        self.nb.AddPage(page, u'直送计划',True)
        
    def showExpense(self):
        
        import PanelExpense 
        
        title = u'费用支出'
        
        for i in range(self.nb.GetPageCount()):
            if (self.nb.GetPageText(i) == title):
                self.nb.SetSelection(i)
                return
                        
        p = PanelExpense.PanelExpense(self.nb)
        self.nb.AddPage(p, title, True)

    
        
